/**
 * 八字记录模型
 * 定义八字计算记录的数据结构
 */

const { DataTypes } = require('sequelize');
const { logInfo, logError } = require('../logger');
const { sequelize } = require('../config/database');
const { User } = require('./User');

/**
 * 八字记录模型定义
 */
const BaziRecord = sequelize.define('BaziRecord', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.BIGINT,
    allowNull: false,
    field: 'user_id',
    references: {
      model: User,
      key: 'id'
    }
  },
  calculationHash: {
    type: DataTypes.STRING(64),
    allowNull: false,
    field: 'calculation_hash'
  },
  inputParams: {
    type: DataTypes.JSON,
    allowNull: false,
    field: 'input_params'
  },
  calculationResult: {
    type: DataTypes.JSON,
    allowNull: false,
    field: 'calculation_result'
  },
  isFavorite: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    field: 'is_favorite'
  }
}, {
  tableName: 'bazi_records',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      fields: ['user_id']
    },
    {
      fields: ['calculation_hash']
    },
    {
      fields: ['is_favorite']
    }
  ]
});

// 建立模型关联
User.hasMany(BaziRecord, {
  foreignKey: 'user_id',
  as: 'baziRecords'
});

BaziRecord.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
});

module.exports = {
  BaziRecord
};